﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SuperSocket;
using SuperSocket.Channel;
using SuperSocket.Command;
using SuperSocket.ProtoBase;

namespace Demo005
{
    class Program
    {
        static async Task Main(string[] args)
        {


             
            
            var host = SuperSocketHostBuilder.Create<ModbusPackageInfo, ModbusPipelineFilter>()
               
                .UseSession<ModbusAppSession>()
               // .UsePackageDecoder<ModbusPackageDecoder>()
                // .UseCommand(options =>
                // {
                //    
                //     options.AddCommand<ReadHoldingRegistersAsyncCommand>();
                //     options.AddGlobalCommandFilter<HoldingRegistersCommandFilterAttribute>();
                // })
               
                 .UsePackageHandler(async (session, package) =>
                {
                    
                    
                    
                    Console.WriteLine($"{package.Body.Length}  = {package.Len}");
 
                    
                    if (package.Key != 0x03||package.Body.Length!=package.Len)
                    {
                      await  session.SendAsync(Encoding.UTF8.GetBytes("不符合规范"));

                       
                    }
                    else
                    {
                        await session.SendAsync(package.Body);
                    }
                    
                    
                })
               .ConfigureLogging(builder => builder.AddConsole())
                .ConfigureServices(
                    services =>
                    {
                          
                        // services.Replace(ServiceDescriptor.Singleton<IPackageDecoder<ModbusPackageInfo>, ModbusPackageDecoder>());
                         services.Configure<ServerOptions>(options =>
                        {
                            
                            options.Name = "Echo Server";
                            options.Listeners = new List<ListenOptions>()
                            {
                                
                                new ListenOptions
                                {
                                    Ip = "Any",
                                    Port = 4040
                                }
                            };
                        });

                    }).Build();

            await host.RunAsync();
        }
    }
}